import React from "react";
import {NavBar, Input, Button, Divider, Toast  } from 'antd-mobile';
import './Login.less';
import axios from 'axios';

export default function Login(props) {
    //受控组件
    let [phone, setPhone] = React.useState('');
    let [code, setCode] = React.useState('');

    //声明函数
    let getCode = async () => {
      //获取手机号 phone
      //判断手机号的格式
      let reg = /^1\d{10}$/;
      //判断 如果格式不正确
      if(!reg.test(phone)){
        //提示
        return Toast.show({
          icon: 'fail',
          content: '名称已存在',
        })
      }
      //发送 AJAX 请求
      try{
        let result = await axios.post('/login/digits', {phone});
        if(result.data.code === 20000){
          Toast.show({
            icon: 'success',
            content: '验证码发送成功'
          })
        }else{
          Toast.show({
            icon: 'fail',
            content: '验证码发送失败'
          })
        }
      }catch(e){
        Toast.show({
          icon: 'fail',
          content: '网络请求异常'
        })
      }
      
    }

    //登录操作
    let login = async () => {
      // console.log('登录');
      let result = await axios.post('/login/phone', {phone, code});
      if(result.data.code === 20000){
        Toast.show({
          icon: 'success',
          content: '登录成功'
        });
        //跳转
        props.history.push('/usercenter');
      }else{
        Toast.show({
          icon: 'fail',
          content: '登录失败'
        });
      }
    }

    return <div className="login-container">
      {/* 顶部导航栏 start */}
      <NavBar back={null}>手机验证码登录</NavBar>
      {/* 顶部导航栏 end */}

      {/* 表单区域 start */}
      <div className="form">
          <div className="phone"><Input onChange={(e) => {
              setPhone(e);
          }} value={phone} clearable placeholder='请输入手机号' /></div>
          <div className="h-20"></div>
          <div className="code">
            <Input value={code} onChange={e => setCode(e)} placeholder="输入验证码" clearable /> 
            <Button size='small' onClick={getCode}>获取验证码</Button>
          </div>
          <div className="h-20"></div>
          <div className="h-10"></div>
          <div className="login">
            <Button block color='danger' size="large" onClick={login}>登录</Button>
          </div>
      </div>
      {/* 表单区域 end */}
      <div className="h-50"></div>
      {/* 其他登录方式 start */}
      <div className="other-login">
        <Divider>其他登录方式</Divider>
        <div className="h-20"></div>
        <div className="h-10"></div>
        <div className="social">
          <img src="/images/github.png" alt="" />
          <img src="/images/qq.png" alt="" />
          <a href="http://localhost:8160/wechat/login"><img src="/images/wechat.png" alt="" /></a>
        </div>
      </div>
      {/* 其他登录方式 end */}

      <p className="yinsi">
        未注册的手机号, 验证后会自动创建硅谷账号, 登录即代表您同意 <a href="http://atguigu.com">《硅谷隐私政策》</a>
      </p>

    </div>;
}
